import pymysql  # 导入模块
import time
# 刘世琪的技术博客

class MySQL():
    print('正在连接到mysql服务器...')
    time.sleep(5)

    def connect(self):

        '''连接MySQL数据库'''
        try:
            db = pymysql.connect(
                host='localhost',
                port=3306,
                user='root',
                passwd='root',
                db='sra201',
                charset='utf8'
            )
            return db
        except:
            raise Exception("数据库连接失败")

    print('连接上了!')
    time.sleep(5)

    def implement(self):
        print('正在获取数据，请稍后...')
        time.sleep(5)
        '''执行SQL语句'''
        db = self.connect()
        cursor = db.cursor()
        for i in range(1):
            sql = """select * from test"""
            try:
                cursor.execute(sql)
                # result = cursor.fetchone() # 单条数据
                result = cursor.fetchall()  # 多条数据
                print('获取数据成功')
                for each in result:
                    db.commit()
                    # time.sleep(5)
                    print('查询结果:', each)

            except:
                db.rollback()
                print("查询失败")

        cursor.close()
        db.close()


# if __name__ == '__main__':
a = MySQL()
a.implement()
